package com.example.querydsl.controller;

import com.example.querydsl.entity.GoodEntity;
import com.example.querydsl.entity.QGoodEntity;
import com.example.querydsl.entity.QGoodTypeEntity;
import com.example.querydsl.repository.GoodRepository;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lombok.extern.slf4j.Slf4j;


/**
 * @Author Anita
 * @Date 2017/12/20 13:25
 */
@RestController
@Slf4j
public class QueryController {

    @Autowired
    private GoodRepository goodRepository;

    @Autowired
    @PersistenceContext
    private EntityManager entityManager;



    @RequestMapping("/query")
    public List<GoodEntity> list(){

        //querydsl 查询实体
        QGoodEntity _good = QGoodEntity.goodEntity;
        //构建JPA查询对象
        JPAQuery<GoodEntity> jpaQuery = new JPAQuery<>(entityManager);
        //返回查询接口
        return jpaQuery.select(_good).from(_good).where(_good.id.eq(Long.valueOf(1))).fetch();
    }

    @RequestMapping("/joinFirst")
    public List<GoodEntity> joinFirst(){
        //查询实体
        QGoodEntity _good = QGoodEntity.goodEntity;
        //查询条件
        BooleanExpression expression = _good.id.eq(Long.valueOf(1));
        //执行查询
        Iterator<GoodEntity> iterator = goodRepository.findAll(expression).iterator();
        List<GoodEntity> goods = new ArrayList<>();
        while(iterator.hasNext()){
            goods.add(iterator.next());
        }
        return goods;
    }
    @RequestMapping("/join")
    public List<GoodEntity> join(){
        //querydsl查询实体
        QGoodEntity _good = QGoodEntity.goodEntity;
        //自定义查询对象
        Inquirer inquirer = new Inquirer();
        inquirer.putExpression(_good.id.eq(Long.valueOf(1)));
        return inquirer.iteratorToList(goodRepository.findAll(inquirer.buildQuery()));
    }



}
